package com.zzb.myshowme.view.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zzb.myshowme.MyApplication;
import com.zzb.myshowme.R;
import com.zzb.myshowme.bean.UserInfo;
import com.zzb.myshowme.bean.UserProfileInfo;
import com.zzb.myshowme.utils.UserInfoUtils;
import com.zzb.myshowme.utils.Base64ImageUtils;
import com.zzb.myshowme.utils.HttpManager;
import com.zzb.myshowme.wiget.CustomAlertDialog;
import com.zzb.myshowme.wiget.ProgressDialogView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import rx.Subscriber;

public class UserInformationActivity extends BaseActivity implements View.OnClickListener{

    ImageView back_imageV;
    ImageView user_imageV;
    TextView nickname_textV, phone_textV, gender_textV, birthday_textV, region_textV, enter_textV;

    RelativeLayout photo_layout, nickname_layout, phone_layout, password_layout, gender_layout;
    RelativeLayout birthday_layout, region_layout, signature_layout, enter_layout;

    private String userPhoto, nickName, sex, birthday, phone, location, signature;
    private int checkedItem = -1;//设置性别

    private DatePickerDialog DatePickerDialog;
    private SimpleDateFormat dateFormatter;
    private Calendar newCalendar;

    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果

    public static final int USERINFO_REQUEST_CODE = 3;
    public static final int USERINFO_RESULT_CODE = 4;

    boolean enter_bool;//有资料修改 为true

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_information);
        dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        newCalendar = Calendar.getInstance();
        initView();
        getDataFromIntent();
        initData();
    }

    private void initView(){

        ProgressDialogView.Initial(this, "提交资料", true);

        back_imageV = (ImageView) findViewById(R.id.back_imageV);
        user_imageV = (ImageView) findViewById(R.id.user_imageV);

        nickname_textV = (TextView) findViewById(R.id.nickname_textV);
        phone_textV = (TextView) findViewById(R.id.phone_textV);
        gender_textV = (TextView) findViewById(R.id.gender_textV);
        birthday_textV = (TextView) findViewById(R.id.birthday_textV);
        region_textV = (TextView) findViewById(R.id.region_textV);
        enter_textV = (TextView) findViewById(R.id.enter_textV);

        enter_layout = (RelativeLayout)findViewById(R.id.enter_layout);
        photo_layout = (RelativeLayout) findViewById(R.id.photo_layout);
        nickname_layout =  (RelativeLayout) findViewById(R.id.nickname_layout);
        phone_layout = (RelativeLayout) findViewById(R.id.phone_layout);
        password_layout = (RelativeLayout) findViewById(R.id.password_layout);
        gender_layout = (RelativeLayout) findViewById(R.id.gender_layout);
        birthday_layout = (RelativeLayout) findViewById(R.id.birthday_layout);
        region_layout = (RelativeLayout) findViewById(R.id.region_layout);
        signature_layout = (RelativeLayout) findViewById(R.id.signature_layout);

        back_imageV.setOnClickListener(this);
        enter_layout.setOnClickListener(this);
        photo_layout.setOnClickListener(this);
        nickname_layout.setOnClickListener(this);
        phone_layout.setOnClickListener(this);
        password_layout.setOnClickListener(this);
        gender_layout.setOnClickListener(this);
        birthday_layout.setOnClickListener(this);
        region_layout.setOnClickListener(this);
        signature_layout.setOnClickListener(this);

    }

    /**
     * 获取数据
     */
    private void getDataFromIntent() {
        Intent intent = getIntent();
        userPhoto = intent.getStringExtra("userPhoto");
        nickName = intent.getStringExtra("nickName");
        birthday = intent.getStringExtra("birthday");
        sex = intent.getStringExtra("sex");
//        checkedItem = (getString(R.string.profile_female).equals(sex)) ? 1 : 0;
        checkedItem = ("男".equals(sex)) ? 0 : 1;
        phone = intent.getStringExtra("phone");
        location = intent.getStringExtra("location");
        signature = intent.getStringExtra("signature");

    }

    private void initData() {
        enter_bool = false;
        if (!TextUtils.isEmpty(userPhoto)) {
            user_imageV.setImageBitmap(Base64ImageUtils.getBitmapFromBase64String(userPhoto));
        }else {
            user_imageV.setImageResource(R.drawable.photo_default);
        }

        nickname_textV.setText(nickName);
        phone_textV.setText(phone);
        gender_textV.setText(sex);
        birthday_textV.setText(birthday);
        region_textV.setText(location);
    }

    private void showSexDialog() {
        final String[] items = new String[2];
        items[0] = "男";
        items[1] = "女";
        final AlertDialog.Builder alert = new AlertDialog.Builder(this);
//        alert.setTitle(getString(R.string.profile_select_sex));
        alert.setTitle("设置性别");
        String sexStr = gender_textV.getText().toString().trim();
//        if (getString(R.string.profile_female).equals(sexStr)) {
        if ("男".equals(sexStr)) {
            checkedItem = 0;
        } else {
            checkedItem = 1;
        }
        alert.setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which != -1) {
                    gender_textV.setText(items[which]);
                    if(checkedItem != which){
                        enter_bool = true;
                    }
                    checkedItem = which;
                }
                dialog.dismiss();
            }
        });
        alert.show();
    }

    /**
     * 设置生日日期
     */
    private void showDatepicker() {
        DatePickerDialog = new DatePickerDialog(this, android.R.style.Theme_Holo_Light_Dialog_NoActionBar, new android.app.DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                newCalendar.set(year, monthOfYear, dayOfMonth);
//                birthday_textV.setText(dateFormatter.format(newCalendar.getTime()));
//                enter_bool = true;
            }

        }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
        DatePickerDialog.setCancelable(true);
        DatePickerDialog.setCanceledOnTouchOutside(true);
        DatePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        birthday_textV.setText(dateFormatter.format(newCalendar.getTime()));
                        enter_bool = true;
                    }
                });
        DatePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePickerDialog.dismiss();
                    }
                });
        DatePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        DatePickerDialog.show();
    }

    /**
     * 设置昵称
     */
    private void showNickNameDialog() {
        final EditText contentView;
        contentView = new EditText(this);
        contentView.setGravity(Gravity.CENTER);

        AlertDialog.Builder mMaterialDialog = new AlertDialog.Builder(this).setTitle("修改昵称").setView(contentView);
        mMaterialDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String nickname = contentView.getText().toString();
                if (nickname.length() > 10 || nickname.length() < 2) {
                    Toast.makeText(UserInformationActivity.this, "名字的长度为3~10之间", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    nickname_textV.setText(nickname);
                    enter_bool = true;
                    dialog.dismiss();
                }
            }
        });
        mMaterialDialog.setNegativeButton("取消", null);

        mMaterialDialog.show();
    }


    /**
     * 设置头像
     */
    private void showPhotoDialog(){
        List<String> items = new ArrayList<String>();
        items.add("拍照");
        items.add("相册");
        CustomAlertDialog customAlertDialog = new CustomAlertDialog(this, null, items);
        customAlertDialog.init(new CustomAlertDialog.OnItemClickListner() {
            @Override
            public void onClick(int position) {
                switch (position) {
                    case 0:
                        // 调用系统的照相机
//                        imageName = getNowTime() + ".png";
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        // 指定调用相机拍照后照片的储存路径
//                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(FXConstant.DIR_AVATAR, imageName)));//将拍取的照片保存到指定URI
                        startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
                        break;
                    case 1:
                        //打开手机的图库;
//                        Intent intent2 = new Intent(Intent.ACTION_PICK, null);
//                        intent2.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
                        intent2.setType("image/*");
                        startActivityForResult(intent2, PHOTO_REQUEST_GALLERY);
                        break;
                }
            }
        });
    }

    private void startPhotoZoom(Uri uri, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("return-data", true);// 返回数据

//        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(FXConstant.DIR_AVATAR, imageName)));//将裁切的结果输出到指定的Uri
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());//裁切成的图片的格式
        intent.putExtra("noFaceDetection", true); // no face detection
        intent.putExtra("scale", true);//支持缩放
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    /**
     * 获取到的图片
     */
    private Bitmap bitmap = null;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_TAKEPHOTO:
//                    startPhotoZoom(Uri.fromFile(new File(FXConstant.DIR_AVATAR, imageName)), 480);
//                    startPhotoZoom(data.getData(), 300);//要先将图片保存在本地 再从本地加载去裁剪，这样直接去裁剪会报错
                    //暂时以下为不裁剪 直接显示图片
                    if (data != null) {
                        Bundle bundle = data.getExtras();
                        bitmap = bundle.getParcelable("data");
                        user_imageV.setImageBitmap(bitmap);
                    } else {
                        return;
                    }
                    break;

                case PHOTO_REQUEST_GALLERY:
                    if (data != null){
                        startPhotoZoom(data.getData(), 300);
                    }else {
                        return;
                    }
                    break;

                case PHOTO_REQUEST_CUT:
                    Bundle bundle = data.getExtras();
                    //得到图片
                    bitmap = bundle.getParcelable("data");
                    user_imageV.setImageBitmap(bitmap);
                    enter_bool = true;
                    break;
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private String Baser64Image = "";
    /**
     * 提交数据
     */
    private void confirmData() {
        if (enter_bool) {
            //提交显示
            ProgressDialogView.show();
            enter_textV.setTextColor(getResources().getColor(R.color.greenyellow));

            UserProfileInfo userProfileInfo = new UserProfileInfo();

            if (bitmap != null) {
                Baser64Image = Base64ImageUtils.getBase64FromBitmap(bitmap);
            } else {
                Baser64Image = userPhoto;
            }

            userProfileInfo.setNickName(nickname_textV.getText().toString().trim());
            userProfileInfo.setUserPhoto(Baser64Image);
            Log.d("test", "Baser64Image " + Baser64Image);
            userProfileInfo.setUser(phone_textV.getText().toString().trim());
            userProfileInfo.setSex(gender_textV.getText().toString().trim());
            userProfileInfo.setBirthday(birthday_textV.getText().toString().trim());
            userProfileInfo.setLocation(region_textV.getText().toString().trim());

//            HttpManager.getInstance().doHttpRequest(HttpManager.getInstance().getHttpService().setUserProfileInfo(userProfileInfo), new Subscriber<String>() {
            HttpManager.getInstance().doHttpRequest(HttpManager.getInstance().getHttpService().testReq(), new Subscriber<String>() {
                @Override
                public void onCompleted() {
                    ProgressDialogView.dismiss();
                    Log.d("upload", "onCompleted down 成功======");

                }

                @Override
                public void onError(Throwable e) {
                    ProgressDialogView.dismiss();
                    Log.d("down", "onError 上传头像======" + e.getMessage());
                    Toast.makeText(UserInformationActivity.this, "网络连接失败，请查看网络设置", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onNext(String string) {
                    ProgressDialogView.dismiss();
                    Toast.makeText(UserInformationActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                    setResultData();
                }
            });
        }else{
            Toast.makeText(UserInformationActivity.this, "资料未修改", Toast.LENGTH_SHORT).show();
        }
    }

    private void setResultData() {

        //独处本地数据再改写
        UserInfo userinfo = UserInfoUtils.readLoginMember(MyApplication.getInstance());
        userinfo.setNickName(nickname_textV.getText().toString().trim());
        userinfo.setUserPhoto(Baser64Image);
        userinfo.setUser(phone_textV.getText().toString().trim());
        userinfo.setSex(gender_textV.getText().toString().trim());
        userinfo.setBirthday(birthday_textV.getText().toString().trim());
        userinfo.setLocation(region_textV.getText().toString().trim());
        UserInfoUtils.writeLoginMember(MyApplication.getInstance(), userinfo);

        Intent intent = new Intent();
        intent.putExtra("Baser64Image", Baser64Image);
        intent.putExtra("nickName", nickname_textV.getText().toString().trim());
        intent.putExtra("birthday", birthday_textV.getText().toString().trim());
        intent.putExtra("sex", gender_textV.getText().toString().trim());
        intent.putExtra("phone", phone_textV.getText().toString().trim());
        intent.putExtra("location", region_textV.getText().toString().trim());
        intent.putExtra("signature", signature);
        setResult(USERINFO_RESULT_CODE, intent);
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_imageV:
//                setResultData();
                finish();
                break;
            case R.id.enter_layout:
                confirmData();
                break;
            case R.id.photo_layout:
                showPhotoDialog();
                break;
            case R.id.nickname_layout:
                showNickNameDialog();
                break;
            case R.id.phone_layout:
                gotoChangeInformation("phone");
                break;
            case R.id.password_layout:
                gotoChangeInformation("password");
                break;
            case R.id.gender_layout:
                showSexDialog();
                break;
            case R.id.birthday_layout:
                showDatepicker();
                break;
            case R.id.region_layout:
                break;
            case R.id.signature_layout:
                break;
        }
    }

    /**
     * 跳转到修改手机号和密码的界面
     */
    private void gotoChangeInformation(String type) {
        Intent intent = new Intent(this, ChangeInformationActivity.class);
        intent.putExtra("type", type);
        startActivity(intent);
    }
}
